package com.demo.servlet.demo1209;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/demo1209/download01.do")
public class Download01Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收文件名参数
        //如果请求中文出现乱码 使用这一句 如果后端能够正常接收中文参数 可以不用
//        String filename = new String(request.getParameter("filename").getBytes("ISO-8859-1"), "UTF-8");
        String filename = request.getParameter("filename");
        //2.完成文件下载
        //2.1 设置 Content-Type 响应头
        //**重要 通过带后缀的 完整的文件名 计算出当前需要响应的文件的MIME类型
        String type = this.getServletContext().getMimeType(filename);
        //设置响应头
        response.setHeader("Content-Type", type);
        //2.2 设置 Content-Disposition 响应头
        //中文文件乱码问题解决
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        //        2.3 设置 文件的输入流 InputStream
        //下载的路径 路径可以是指定某个文件夹专门用于存放下载资源
        String downloadPath = "D:\\download\\" + filename;
        //基于路径创建输入流
        FileInputStream fis = new FileInputStream(downloadPath);
        // 获取 response 输出流
        ServletOutputStream os = response.getOutputStream();
        //IO流固定模板
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fis.read(buffer)) != -1) {
            os.write(buffer, 0, length);
            os.flush();
        }
        //只要关闭输入流即可
        fis.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //不管外部是get 还是 post  请求 都调用同一段逻辑
        doGet(request, response);
    }
}
